<?php

namespace XWAM\Addon\PXCallSystem\Controller;

/**
 * 短信控制器
 *
 * @author Alen
 * @since 1.0 2014-9-18 by sutroon
 */
class SMSController extends AppbaseController {

    public function strategycall_sms_list() {
        $this->display();
    }
    public function get_strategycall_sms_list_json(){
        $this->get_call_sms_list_json('strategy');
    }

    public function extensioncall_sms_list(){
        $this->display();
    }
    public function get_extensioncall_sms_list_json() {
        $this->get_call_sms_list_json('extension');
    }

    public function get_call_sms_search_data($tag){
        // 只显示生成的任务
        if (!$this->isSuperAdmin) {
            $where['siteID'] = $this->loginData['siteID'];
        }
        $where['exTags'] = $tag;
        $where['source'] = 'generate';
        return array('where'=>$where);
    }
    public function get_call_sms_list_json($tag){        
        $search_data=$this->get_call_sms_search_data($tag);
        $where=$search_data['where'];
        $orderby = I('sort', 'id') . ' ' . I('order');
        $page = I('page', 1) . ',' . I('rows', C('USER.PAGE_SIZE'));
        $M=M('vsms_task_' . $tag);
        $total = $M->cache(true)->where($where)->count('id');
        $list = $M->cache(true)->field('id,siteID,serverName,taskStrategyName,taskStrategyDurationEnable,taskStrategyDuration,seatdtmfEnable,seatdtmf,message,sign,state,createdTime')->where($where)->order($orderby)->page($page)->select();
        $out = array();
        foreach ($list as $row) {
            $row['siteIDText'] = get_siteID_text($row['siteID']);
            $out[] = $row;
        }
        $this->ajaxReturn(array('total' => $total, 'rows' => $out));
    }

    public function strategycall_sms_edit() {
        $this->call_sms_edit();
    }

    public function extensioncall_sms_edit() {
        $this->call_sms_edit();
    }

    public function call_sms_delete($id='',$tag='') {
        if (!$id || !$tag) {
            $this->ajaxMsg(false, '参数有误!');
        }
        $result = M('tsms_task')->delete($id);
        $this->ajaxMsg($result, '删除{%}');
    }

    function call_sms_edit($id=0) {
        if ($id) {
            $data = M('tsms_task')->find($id);
            $this->assign('data', $data);
        }
        $this->display();
    }

    function call_sms_save() {
        $tag = I('exTags');
        $params = new \Org\Su\Params();
        $params->addParam('exTags', 'require', '类型无效!');
        $params->addParam('siteID', 'number', '租户未选择!');
        $params->addParam('serverID', 'number', '短信服务器未选择!');
        if ($tag == 'strategy') {
            $params->addParam('taskStrategyID', 'number', '任务策略必须选择!');
            // 策略外呼时长
            $taskStrategyDurationEnable = I('taskStrategyDurationEnable');
            if ($taskStrategyDurationEnable == '1') {
                $params->addParam('taskStrategyDuration', 'number', '策略外呼时长必须填写!');
            } else {
                $params->addData('taskStrategyDuration', 0);
            }
            $params->addData('taskStrategyDurationEnable', $taskStrategyDurationEnable == '1' ? 1 : 0);
            // 分机按键
            $seatdtmfEnable = I('seatdtmfEnable');
            if ($seatdtmfEnable == '1') {
                $params->addParam('seatdtmf', 'require', '分机按键必须填写!');
            } else {
                $params->addData('seatdtmf', '');
            }
            $params->addData('seatdtmfEnable', $seatdtmfEnable == '1' ? 1 : 0);
        } else {
            $params->addParam('extensions', 'require', '分机号码必须填写!');
            $params->addParam('extensionDuration', 'number', '分机外呼时长必须填写!');
        }
        $params->addParam('message', 'require', '短信内容必须填写!');
        $params->addParam('sign', 'require', '短信签名必须填写!');
        $params->addParam('state', 'number', '状态未选择!');
        if ($params->hasError()) {
            $this->ajaxMsg(false, $params->getError());
        }
        $id = I('id');
        $M = M('tsms_task');
        if ($id) {
            $result = $M->where('id=' . $id)->save($params->getParams());
        } else {
            $params->addData('source', 'generate');
            $params->addData('createdTime', date('Y-m-d H:i:s'));
            $result = $M->add($params->getParams());
        }
        if ($result === false) {
            $this->ajaxMsg(false, '保存失败');
        } else {
            $this->ajaxMsg(true, '保存成功');
        }
    }

    public function sms_import() {
        // 只显示未发送的
        $where = "source in ('add','import') and state=0";
        if (!$this->isSuperAdmin) {
            $where .= ' and siteID=' . $this->loginData['siteID'];
        }
        $list = AddonD('CDR')->get_paging_list($where, $show,array('TABLE'=>'vsms_queue'));
        $this->assign('list', sofn_set_site_id_text($list));
        $this->assign('page', $show);
        $this->display();
    }

    public function sms_import_save() {
        $source = I('source');
        $params = new \Org\Su\Params();
        $params->addParam('source', 'require', '操作类型未选择!');
        if ($source == 'add') {
            $params->addParam('phoneNumber', 'require', '手机号码必须填写!');
            $taskName = I('phoneNumber');
        }
        $params->addParam('siteID', 'number', '租户未选择!');
        $params->addParam('serverID', 'number', '短信服务器未选择!');
        $params->addParam('message', 'require', '短信内容必须填写!');
        $params->addParam('sign', 'require', '短信签名必须填写!');
        if ($params->hasError()) {
            $this->ajaxMsg(false, $params->getError());
        }
        if (!sofn_check_user_blance_state(I('siteID'))) {
            $this->ajaxMsg(false, '您的可用余额不足，请充值!', AddonU('Recharge/index'));
        }

        // 上传文件
        if ($source == 'import') {
            $msg = sofn_upload_handle(array('savePath' => 'SMS/Import/', 'exData' => array('createdTime' => date('Y-m-d H:i:s'), 'exTags' => 'import-sms', 'siteID' => I('siteID'))));
            if (!is_array($msg)) {
                $this->ajaxMsg(false, $msg);
            }
            if (strpos(',xls,xlsx,cvs,', $msg['fileExt']) === false) {
                $content = file_get_contents(UPLOAD_ROOT . $msg['filePath']);
                $arrcontent = explode("\n", $content);
            } else {
                $arrcontent = sofunc_excel_import(UPLOAD_ROOT . $msg['filePath']);
            }
            $taskName = $msg['fileName'];
        }

        $params->addData('createdTime', date('Y-m-d H:i:s'));
        $params->addData('taskName', $taskName);
        $tid = M('tsms_task')->add($params->getParams());
        if ($tid === false) {
            $this->ajaxMsg(false, '保存失败');
        } else {
            $M = M('tsms_queue');
            if ($source == 'import') {
                $message = I('message');
                $sign = I('sign');
                $siteID = I('siteID');
                $serverID = I('serverID');
                $arrsql = array();
                $i = 0;
                foreach ($arrcontent as $item) {
                    if (trim($item) == '') {
                        continue;
                    }
                    $arrsql[] = sprintf("(%d, %d, '%s', '%s', '%s', 'import', now(), %d)", $tid, $serverID, $item, $message, $sign, $siteID);
                    if ($i > 0 && $i % 300 == 0) {
                        $result = $M->execute('insert into tsms_queue (taskID, serverID, phoneNumber, message, sign, source, createdTime, siteID) values ' . implode(',', $arrsql));
                        empty($arrsql);
                    }
                    $i++;
                }
                if ($arrsql) {
                    $result = $M->execute('insert into tsms_queue (taskID, serverID, phoneNumber, message, sign, source, createdTime, siteID) values ' . implode(',', $arrsql));
                }
            } else {
                $params->removeParam('taskName');
                $params->addData('taskID', $tid);
                $result = $M->add($params->getParams());
            }
            if ($result === false) {
                $this->ajaxMsg(false, '保存失败' . $M->getDbError());
            } else {
                $this->ajaxMsg(true, '保存成功', AddonU('SMS/sms_send_batch', array('id' => $tid)));
            }
        }
    }

    public function sms_send_batch() {
        $debug = I('debug');
        $id = I('id');
        if (!$id) {
            die('参数有误!');
        }
        $task = M('tsms_task')->find($id);
        if (!$task) {
            $this->ajaxMsg(false, '记录不存在!');
        }
        if (!$this->isSuperAdmin && !$task['siteID'] != $this->loginData['siteID']) {
            $this->ajaxMsg(false, '无权操作!');
        }
        echo '<div style="font-size:12px;"><a href="' . AddonU('SMS/sms_import') . '" target="_blank">[查看导入的短信]</a> <strong>正在发送短信...</strong><div style="height:640px; overflow-y:scroll">';
        $strCompanyID = '3268';
        $strUserName = 'xmxyx';
        $strPassword = '123456qwe';
        $strCompanyName = '鑫优轩';
        $uri = "http://inter.ueswt.com/smsGBK.aspx?userid=$strCompanyID&account=$strUserName&password=$strPassword&action=send";
        $M = M('tsms_queue');
        $sql = $debug ? "taskID=$id" : "taskID=$id and state not in (1,4)";
        $list = $M->where($sql)->select();
        $limit = 6;

        //$conn = mysql_connect(C('DB_HOST'), C('DB_USER'), C('DB_PWD')) or die(mysql_error());
        //mysql_select_db(C('DB_NAME'), $conn) or die(mysql_error());
        //mysql_query('set names utf8');
        foreach ($list as $row) {
            if ($debug) {
                var_dump($row);
                die($uri . '&mobile=' . $row['phoneNumber'] . '&content=' . $row['message'] . '[' . $row['sign'] . ']');
            }
            if ($row['state'] == '4') {
                continue;
            }
            if ($row['sendCount'] > 5) {
                $M->where('id=' . $row['id'])->setField('state', 4);
                continue;
            }
            $content = $row['message'] . '【' . $row['sign'] . '】';
            $uritemp = $uri . '&mobile=' . $row['phoneNumber'] . '&content=' . iconv('UTF-8', 'GB2312//IGNORE', $content);
            $msg = $this->get_getData($uritemp); // 返回1或0
            $blnmsg = strpos($msg, 'ok') !== false;
            $result = mysql_query('call proc_update_smsqueue_amount(' . $row['siteID'] . ',' . $row['id'] . ',' . ($blnmsg ? 1 : 2) . ')') or die(mysql_error());
            if ($result === false) {
                die('更新数据库失败!' . $M->getDbError());
            }
            echo '发送' . $row['phoneNumber'] . ($blnmsg ? '成功' : '失败') . '<br />';
        }
        echo '</div></div>';
    }

    function get_getData($url) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        return $output;
    }

    public function test_send() {
        $msg = $this->get_getData('http://117.25.177.102:8899/xcall/index.php?s=SMS/test_send/name/sutroon/id/5.html');
        echo 'msg:' . $msg;
    }

    public function test_get() {
        file_put_contents('F:\\test_get.txt', 'msg:id=' . I('id') . ',name=' . I('name'));
        echo 'ok ' . I('name');
    }

    public function server_list() {
        $this->display();
    }
    public function get_server_list_json(){        
        if (!$this->isSuperAdmin) {
            $where['siteID'] = $this->loginData['siteID'];
        }
        $list = AddonD('SMS')->get_server_list($where);
        $this->ajaxReturn($list);
    }

    /**
     * 导出数据
     * @since 1.0 <2015-7-2> SoChishun Added.
     */
    public function server_export() {
        if (!$this->isSuperAdmin) {
            die('没有权限!');
        }
        $list = AddonD('SMS')->scope('server_export')->select();
        if (!$list) {
            $this->ajaxMsg(false,'找不到符合条件的记录!');
        }
        sofn_excel_export($list);
    }

    public function server_edit($id=0) {
        if ($id) {
            $data = M('tsms_server')->find($id);
            $this->assign('data', $data);
        }
        $this->display();
    }

    public function server_edit_save() {
        $params = new \Org\Su\Params();
        $params->addParam('siteID', 'number', '租户未选择!');
        $params->addParam('serverName', 'require', '服务器名称必须填写!');
        $params->addParam('host', 'require', '服务器地址必须填写!');
        $params->addParam('port', 'number', '端口号必须填写!');
        //$params->addParam('loginID', 'require', '账户必须填写!');
        //$params->addParam('password', 'require', '密码必须填写!');
        $params->addParam('contentLength', 'number', '内容最大字符数必须填写!');
        $params->addParam('sendInterval', 'number', '发送间隔必须填写!');
        if ($params->hasError()) {
            $this->ajaxMsg(false, $params->getError());
        }
        $params->addData('remark');
        $id = I('id');
        $M = M('tsms_server');
        if ($id) {
            $result = $M->where('id=' . $id)->save($params->getParams());
        } else {
            $params->addData('createdTime', date('Y-m-d H:i:s'));
            $result = $M->add($params->getParams());
        }
        if ($result === false) {
            $this->ajaxMsg(false, '保存失败');
        } else {
            $this->ajaxMsg(true, '保存成功');
        }
    }

    /**
     * 删除服务器
     * @since 1.0 2014-9-29 by sutroon
     */
    public function server_delete($id='') {
        if (!$id) {
            $this->ajaxMsg(false, '参数有误');
        }
        $result = M('tsms_server')->delete($id);
        $this->ajaxMsg($result, '删除{%}');
    }

    /**
     * 获取服务器列表
     */
    public function get_server_json() {
        if ($this->isSuperAdmin) {
            $where['siteID'] = I('siteID');
        } else {
            $where['siteID'] = $this->loginData['siteID'];
        }
        $str = M('tsms_server')->where($where)->getField(array('id', "concat(serverName,'(',host,'|',siteID,')') as text"),true);
        $this->ajaxReturn($str);
    }
    public function send_history() {
        $this->display();
    }
    public function get_sms_send_history_search_data(){
        $search=I();        
        if (!$this->isSuperAdmin) {
            $where['siteID']=$this->loginData['siteID'];
        }
        // 默认显示一周记录
        if(!$search['date']){
            $search['date']=date('Y-m-d');
        }
        $where["date_format(createdTime,'%Y-%m-%d')"]=$search['date'];
        if($search['phoneNumber']){
            $where['phoneNumber']=array('like','%'.$search['phoneNumber'].'%');
        }
        if($search['state']){
            $where['state']=$search['state']?$search['state']:array('in','1,2');
        }
        if($search['siteID']){
            $where['siteID']=$search['siteID'];
        }
        return array('search'=>$search,'where'=>$where);
    }
    public function get_sms_send_history_list_json(){        
        $search_data=$this->get_sms_send_history_search_data();
        $where=$search_data['where'];
        $orderby = I('sort', 'id') . ' ' . I('order');
        $page = I('page', 1) . ',' . I('rows', C('USER.PAGE_SIZE'));
        $M=M('vsms_queue');
        $total = $M->where($where)->count('id');
        $list = $M->field('id,siteID,phoneNumber,state,serverName,smsCount,amount,sendCount,sendTime,sign,message')->where($where)->order($orderby)->page($page)->select();
        $out = array();
        foreach ($list as $row) {
            $row['siteIDText'] = get_siteID_text($row['siteID']);
            $out[] = $row;
        }
        $this->ajaxReturn(array('total' => $total, 'rows' => $out));
    }
    public function sms_send_history_export(){
        $search_data=$this->get_sms_send_history_search_data();
            $list = M('vsms_queue')->field("siteID as '租户ID',phoneNumber as '接收号码',state as '发送状态',serverName as '短信服务器',smsCount as '计费条数',amount as '计费金额',sendCount as '发送次数',sendTime as '发送时间',sign as '短信签名',message as '短信内容'")->where($search_data['where'])->select();
            if (!$list) {
                die('没有符合条件的记录!');
            }
            sofn_excel_export($list);
        
    }

}
